<?php
/**
 * Created By PhpStorm
 * Author: patrick wu
 * Date: 2020/9/29
 * Time: 14:35
 */
namespace App\Service\Admin;

use App\Http\Model\Mysql\ExpressModel;
use App\Http\Model\Mysql\OrderIncomeModel;
use App\Http\Model\Mysql\OrderModel;
use App\Http\Model\Mysql\OrderProductModel;
use App\Http\Model\Mysql\OrderRefundModel;
use App\Http\Model\Mysql\OrderRefundProcessModel;
use App\Http\Model\Mysql\UserModel;
use App\Http\Model\Mysql\CouponModel;
use App\Http\Model\Mysql\UserBindModel;
use App\Jobs\AutoConfirmJob;
use App\User;
use Carbon\Carbon;

class OrderService extends BaseService
{
    /**
     * 订单列表
     * @param array $query
     * @param int $page
     * @param int|null $size
     * @return array
     */
    public function orderList(array $query = [], int $size = NULL, int $page = 1)
    {
        $model  =   OrderModel::query();
        $where['is_delete'] =   OrderModel::NOT_DELETE;

        /**
         * 搜索条件
         */

        //订单号
        if (isset($query['order_no']) && !empty($query['order_no'])) {
            $where['order_no']    =   trim($query['order_no']);
        }

        //快递号
        if (isset($query['express_no']) && !empty($query['express_no'])) {
            $where['express_no']  =   trim($query['express_no']);
        }

        //下单人姓名
        if (isset($query['buyer_name']) && !empty($query['buyer_name'])) {
            $where['buyer_name']  =   trim($query['buyer_name']);
        }

        //下单人手机号
        if (isset($query['buyer_phone']) && !empty($query['buyer_phone'])) {
            $where['buyer_phone'] =   trim($query['buyer_phone']);
        }

        //订单来源
        if (isset($query['order_source']) && !empty($query['order_source'])) {
            $where['order_source'] =   trim($query['order_source']);
        }

        //下单时间
        if (isset($query['start_time']) && !empty($query['start_time'])) {
            $where[]    =   ['created_at', '>=', Carbon::parse($query['start_time'])->timestamp];
        }

        if (isset($query['end_time']) && !empty($query['end_time'])) {
            $where[]    =   ['created_at', '<=', Carbon::parse($query['end_time'])->timestamp];
        }

        //订单状态
        $query_status   =   $query['status'] ?? 1;
        switch ($query_status) {
            case 1:
                break;

            case 2:
                $where['is_pay']    =   OrderModel::NOT_PAY;
                break;

            case 3:
                $where['send_status']=  OrderModel::NOT_SEND;
                break;

            case 4:
                $where['is_confirm']=   OrderModel::NOT_CONFIRM;
                break;

            case 5:
                $where['is_pay']    =   OrderModel::IS_PAY;
                $where['is_confirm']=   OrderModel::IS_CONFIRM;
                $where['order_status']= OrderModel::IS_NORMAL;
                break;

            case 6:
                $where['order_status']= OrderModel::IS_CANCEL;
                break;
        }

        $model  =   $model->where($where);
        //供应商
        if (isset($query['supply_id']) && !empty($query['supply_id'])) {
            $supply =   $query['supply_id'];
            $model  =   $model->whereHas('supply', function ($query) use($supply) {
                $query->where('supply_id', '=', $supply);
            });
        }

        $size   =   empty($size) ? self::PAGE_LIMIT : $size;
        $count  =   $model->count();
        $list   =   $model->with([
                        'product'   =>  function ($query) {             //订单产品表
                            $query->with([
                                'spec'  =>  function ($query) {         //产品规格表
                                    $query->select(['id', 'attr_list', 'sell_price', 'sku_code']);
                                },
                                'good'  =>  function ($query) {         //产品详情表
                                    $query->select(['id', 'name', 'sku_code', 'cover_pic', 'sell_price', 'stock', 'unique_id']);
                                }
                            ])->select(['id', 'order_id', 'product_id', 'item_id', 'attr_pic', 'product_count', 'product_total as product_price']);
                        },
                    ])->select(['id', 'user_id', 'box_id', 'order_no', 'pay_time', 'express', 'express_no', 'total_price', 'update_price', 'send_status', 'order_status', 'is_confirm', 'refund_status', 'created_at', 'is_pay', 'coupon_price', 'pay_price', 'buyer_name', 'buyer_phone', 'buyer_province', 'buyer_city', 'buyer_area', 'buyer_address', 'send_time', 'coupon_id', 'pay_transaction'])
                    ->offset(($page - 1) * $size)->limit($size)->get()->each(function (&$item){
                        $item->user_info    =   UserModel::where(['uid' => $item->user_id])->select(['uid', 'nickname', 'phone', 'headimg', 'relname'])->first();
                        $item->pay_time     =   $item->pay_time <= 0 ? '' : Carbon::createFromTimestamp($item->pay_time)->toDateTimeString();
                        $item->send_time    =   $item->send_time <= 0 ? '' : Carbon::createFromTimestamp($item->send_time)->toDateTimeString();
                        $item->created_time =   $item->created_at->toDateTimeString();
                        unset($item->created_at);
                        foreach ($item->product as &$single) {
                            if ($single->spec) {
                                $single->spec->attr_value =   array_values(json_decode($single->spec->attr_list, true));
                            }
                        }
                        //优惠券信息
                        if ($item->coupon_id != 0) {
                            $coupon_info        =   CouponModel::where(['id' => $item->coupon_id])->select(['id', 'name', 'desc', 'picture'])->first();
                            $item->coupon_info  =   empty($coupon_info) ? [] : $coupon_info->toArray();
                        } else {
                            $item->coupon_info  =   [];
                        }

                        //分销商信息
                        $bind_info  =   UserBindModel::where(['bind_user' => $item->user_id, 'bind_type' => UserBindModel::BIND_STRONG])->first();
                        if (empty($bind_info)) {
                            $item->bind_user    =   [];
                        } else {
                            $item->bind_user    =   User::where(['uid' => $bind_info['share_user']])->select(['uid', 'nick_name', 'relname', 'phone'])->first() ?? [];
                        }
                    });

        if ($list->isEmpty()) {
            return [true, []];
        } else {
            return [true, [
                'count' =>  $count,
                'list'  =>  $list->toArray(),
                'pages' =>  ceil($count / $size),
                'current'=> $page
            ]];
        }
    }

    /**
     * 修改商家备注
     * @param int $order_id         订单ID
     * @param string $seller_remark 商家备注
     * @return array
     */
    public function orderRemark(int $order_id, string $seller_remark)
    {
        $update_result  =   OrderModel::where(['id' => $order_id])->update(['seller_remark' => $seller_remark]);
        if ($update_result) {
            return [true, '修改成功'];
        } else {
            return [false, '修改失败'];
        }
    }

    /**
     * 订单详情
     * @param int $order_id     订单ID
     * @return array
     */
    public function orderDetail(int $order_id)
    {
        $info_result    =   OrderModel::with([
            'product'   =>  function ($query) {             //订单产品表
                $query->with([
                    'spec'  =>  function ($query) {         //产品规格表
                        $query->select(['id', 'attr_list', 'sell_price', 'sku_code']);
                    },
                    'good'  =>  function ($query) {         //产品详情表
                        $query->select(['id', 'name', 'sku_code', 'cover_pic', 'sell_price', 'stock', 'unique_id']);
                    }
                ])->select(['id', 'order_id', 'product_id', 'item_id', 'attr_pic', 'product_count', 'product_total as product_price']);
            },
        ])->where(['id' => $order_id, 'is_delete' => OrderModel::NOT_DELETE])->select(['id', 'order_no', 'pay_time', 'express', 'express_no', 'total_price', 'update_price', 'send_status', 'order_status', 'is_confirm', 'refund_status', 'created_at', 'is_pay', 'coupon_price', 'pay_price', 'buyer_name', 'buyer_phone', 'buyer_province', 'buyer_city', 'buyer_area', 'buyer_address', 'send_time', 'coupon_id', 'share_id'])->first();

        if (empty($info_result)) {
            return [false, '订单不存在'];
        } else {
            foreach ($info_result->product as &$item) {
                $item->spec->attr_value =   array_values(json_decode($item->spec->attr_list, true));
            }
            //分销商信息
            $bind_info  =   UserBindModel::where(['bind_user' => $info_result->user_id, 'bind_type' => UserBindModel::BIND_STRONG])->first();
            if (empty($bind_info)) {
                $info_result->bind_user    =   [];
                //分佣奖励
                $info_result->share_price  =   0;
            } else {
                $info_result->bind_user    =   User::where(['uid' => $bind_info['share_user']])->select(['uid', 'nick_name', 'relname', 'phone'])->first() ?? [];
                //分佣奖励
                $info_result->share_price  =   OrderIncomeModel::where(['uid' => $bind_info['share_user'], 'oid' => $info_result->id, 'reward' => OrderIncomeModel::REWARD_PROMOTE])->value('income') ?? 0.00;
            }
            $info_result->created_time     =   $info_result->created_at->toDateTimeString();
            //邀请奖励
            $info_result->invite_price     =   $info_result->share_id == 0 ? 0.00 : (OrderIncomeModel::where(['uid' => $info_result->share_id, 'oid' => $info_result->id, 'reward' => OrderIncomeModel::REWARD_INVITE])->value('income') ?? 0.00);

            //优惠券信息
            if ($info_result->coupon_id != 0) {
                $coupon_info        =   CouponModel::where(['id' => $info_result->coupon_id])->select(['id', 'name', 'desc', 'picture'])->first();
                $info_result->coupon_info  =   empty($coupon_info) ? [] : $coupon_info->toArray();
            } else {
                $info_result->coupon_info  =   [];
            }

            //售后状态
            if ($info_result->order_status == OrderModel::IS_AFTER_SALE) {
                $info_result->after_info    =   OrderRefundModel::where(['order_id' => $info_result->id])->select(['id', 'refund_no', 'refund_type', 'refund_status', 'is_agree'])->first() ?? [];
            } else {
                $info_result->after_info    =   [];
            }
            return [true, $info_result];
        }
    }

    /**
     * 订单退款
     * @param int $order_id
     * @param int $detail_id
     * @param string $cancel_reason
     * @return array
     */
    public function orderRefund(int $order_id, int $detail_id, string $cancel_reason = '')
    {
        $order_info =   OrderModel::where(['id' => $order_id, 'is_delete' => OrderModel::NOT_DELETE])->select(['id', 'user_id', 'order_no', 'pay_price', 'order_status', 'refund_status'])->first();

        if (empty($order_info)) {
            return [false, '订单不存在'];
        }

        if ($order_info->order_status == OrderModel::IS_AFTER_SALE || $order_info->refund_status != OrderModel::APPLY_NORMAL) {
            return [false, '订单售后处理中'];
        }
        /**
         * 订单状态修改
         */
        OrderModel::where(['id' => $order_info->id])->update(['order_status' => OrderModel::IS_AFTER_SALE, 'refund_status' => OrderModel::APPLY_REFUND]);

        /**
         * 售后记录保存
         */
        $order_refund['user_id']    =   $order_info->user_id;
        $order_refund['order_id']   =   $order_info->id;
        $order_refund['detail_id']  =   $detail_id;
        $order_refund['refund_no']  =   createRandomNumber(24);
        $order_refund['refund_type']=   OrderRefundModel::ONLY_REFUND;
        $order_refund['refund_price']=  OrderProductModel::where(['id' => $detail_id, 'uid' => $order_info->user_id, 'order_id' => $order_info->id])->value('product_total') ?? 0;
        $order_refund['reason']     =   $cancel_reason;
        $order_refund['remark']     =   '';
        $order_refund['proof']      =   json_encode([], JSON_UNESCAPED_UNICODE);
        $order_refund['is_receive'] =   0;

        $after_result   =   OrderRefundModel::create($order_refund);

        if ($after_result) {
            OrderRefundProcessModel::create([
                'refund_id'     =>  $after_result->id,
                'operate_user'  =>  0,
                'operate_time'  =>  Carbon::now()->timestamp,
                'operate_type'  =>  $order_refund['refund_type'],
                'operate_function'=>OrderRefundProcessModel::FUNCTION_APPLY,
                'operate_desc'  =>  '退款' . OrderRefundProcessModel::FUNCTION_DESC[OrderRefundProcessModel::FUNCTION_APPLY],
            ]);
            return [true, '申请成功'];
        }
        return [false, '申请失败'];
    }

    /**
     * 订单取消
     * @param int $order_id
     * @param string $cancel_reason
     * @return array
     */
    public function orderCancel(int $order_id, string $cancel_reason = '')
    {
        $can_result =   OrderModel::where(['id' => $order_id])->update(['order_status' => OrderModel::IS_CANCEL, 'system_reason' => $cancel_reason, 'cancel_reason' => 10]);
        if ($can_result) {
            return [true, '取消成功'];
        } else {
            return [false, '取消失败'];
        }
    }

    /**
     * 订单发货
     * @param int $order_id
     * @param int $is_express
     * @param int $express_id
     * @param string $express_no
     * @return array
     */
    public function orderConfirm(int $order_id, int $is_express, int $express_id, string $express_no)
    {
        $order_info =   OrderModel::where(['id' => $order_id])->select(['id', 'send_status', 'order_status', 'order_no'])->first();
        if ($order_info->send_status == OrderModel::IS_SEND) {
            return [false, '订单已发货'];
        }

        if ($is_express == 1) {
            $update =   [
                'express'       =>  ExpressModel::where(['id' => $express_id])->value('express_name') ?? '',
                'express_no'    =>  $express_no,
                'send_status'   =>  OrderModel::IS_SEND,
                'send_time'     =>  Carbon::now()->timestamp
            ];
        } else {
            $update =   [
                'express'       =>  '',
                'express_no'    =>  '',
                'send_status'   =>  OrderModel::IS_SEND,
                'send_time'     =>  Carbon::now()->timestamp
            ];
        }
        $result =   OrderModel::where(['id' => $order_id])->update($update);

        AutoConfirmJob::dispatch($order_info)->onQueue('auto_confirm');
        if ($result) {
            return [true, '发货成功'];
        } else {
            return [false, '发货失败'];
        }
    }

}
